	#include "precomp.h"
	#include "GameObject.h"

	GameObject::GameObject(){}

	GameObject::GameObject(const char* image_path, CL_GraphicContext *gc, Map *map, float collision_radius) 
		: _gc(gc), _map(map), _collision_radius(collision_radius)
	{
		CL_SpriteDescription ch_sd;
		ch_sd.add_frame(image_path);

		_sprite = new CL_Sprite(*gc, ch_sd);
	}

	GameObject::~GameObject(){
		delete _sprite;
	}

	void GameObject::tick(float delta_time){

	}

	float GameObject::get_x(){
		return _x;
	}

	float GameObject::get_y(){
		return _y;
	}

	float GameObject::get_collision_radius(){
		return _collision_radius;
	}

	void GameObject::set_position(float x, float y){
		_x = x;
		_y = y;
	}

	void GameObject::draw(float x, float y){
		if(_sprite == NULL)
			throw CL_Exception("_sprite Not Allocated");

		_sprite->draw(*_gc, x, y);
	}

	bool GameObject::collide_map(){
		CL_Point character_tile_position = _map->get_tile_position(_x, _y);

		//CL_Console::write_line("character_tile_position (%1, %2)", character_tile_position.x, character_tile_position.y);

		CL_Pointf character_positionf(_x + 16, _y + 16);
		float tile_size = _map->get_tile_size();
		int dir[8][2] = {{0,1},{0,-1},{1,0},{1,-1},{1,1},{-1,1},{-1,0},{-1,-1}};
		for(int i=0;i < 8;i++){
			CL_Point tile_position(character_tile_position.x + dir[i][0], character_tile_position.y + dir[i][1]);

			if(_map->in_bound(tile_position.x, tile_position.y)){
				char tile = _map->get_tile(tile_position.x, tile_position.y);

				if(tile == MAP_WALL){
					CL_Pointf tile_positionf(tile_position.x * tile_size + tile_size/2, tile_position.y * tile_size + tile_size/2);
					
					float tile_size_2 = tile_size/2;

					if(tile_positionf.distance(character_positionf) <= _collision_radius + sqrt(2*tile_size_2*tile_size_2)){
						return true;
					}
				}
			}
		}

		return false;
	}